<?php
/**
*	@author SignpostMarv Martin
*	@package UHU
*	@subpackage UHU_exception
*/

/**
*	Acts as a means to turn PHP errors into exceptions
*	@package UHU
*	@subpackage UHU_exception
*/
class uhu_error_exception extends ErrorException
{
/**
*	@param int $errno Error number
*	@param string $errstr Error message
*	@param string|null $errfile The file the error occured in
*	@param integer|null $errline The line the error occured on
*	@param array|null $errcontext The backtrace showing what led to the error occuring
*	@uses ErrorException::__construct
*/
	public static function error($errno,$errstr,$errfile=null,$errline=null)
	{
		$throw = false;
		switch($errno)
		{
			case 2:
				$throw = defined('UHU_ERROR_AS_EXCEPTION') ? (UHU_ERROR_AS_EXCEPTION & E_WARNING) : (uhu_install_config::get('uhu_error_exception::throw::warning') === true);
			break;
			default:
				$throw = true;
			break;
		}
		
		if($throw){ throw new self($errstr,0,$errno,$errfile,$errline); } # alteration due to supressed errors not meant to get thrown
	}
/**
*	decides whether or not to set uhu_error_exception as the error handler
*/
	public static function set()
	{
		if(defined('UHU_ERROR_AS_EXCEPTION'))
		{
			if(UHU_ERROR_AS_EXCEPTION === true)
			{
				set_error_handler('uhu_error_exception::error');
			}
			else if(UHU_ERROR_AS_EXCEPTION !== FALSE)
			{
				set_error_handler('uhu_error_exception::error',UHU_ERROR_AS_EXCEPTION);
			}
		}
	}
}
/**
*	@uses uhu_error_exception::set() to decide whether or not to throw uhu_error_exception::__construct when PHP errors occur.
*/
uhu_error_exception::set();

/**
*	Exception class used by UHU Applications & Components
*	@package UHU
*	@subpackage UHU_exception
**/
abstract class uhu_exception extends Exception
{
/**
*	@var bool set as true if UHU_DEBUG_MODE is enabled
**/
	private $detailed = false;
/**
*	@param string $message Error message
*	@param integer|null $code Error code, or null
**/
	final public function __construct()
	{
		$this->detailed = defined('UHU4_DEBUG_MODE') | defined('UHU_DEBUG_MODE');
		$args = func_get_args();
		if(empty($args))
		{
			parent::__construct();
		}
		else
		{
			switch(count($args))
			{
				case 1:
					parent::__construct($args[0]);
				break;
				default:
					parent::__construct($args[0],$args[1]);
				break;
			}
		}
	}
/**
*	@return string calculates the extended error message, adding detailed information if $this->detailed is set to true
*	@uses uhu_exception::$detailed
**/
	final public function __toString()
	{
		$error = (strlen($this->getMessage()) > 0) ? sprintf(call_user_func_array(array($this,'getExtendedMessage'),array($this->getCode())),$this->getMessage()) : '';
		if($this->detailed)
		{
			return $this->getFile() . ' had an error on line ' . $this->getLine() . ':' . $error;
		}
		else
		{
			return $error;
		}
	}
/**
*	@param int|null $code taken from $this->getCode()
*	@return string an extended error message
*/
	abstract protected function getExtendedMessage($code=null);
}
?>